// 📦 引入工具库
const _ = require("lodash");
const path = require("path");
const fs = require("fs");

// 📦 ESM 支持模块加载
const esm = require("esm");
const requireModule = esm(module);

// 📦 项目依赖模块
const { readAllValues } = requireModule(
  "../../../awakened-potential/helpers/readAllValues.js"
);
const checkAccuracy = requireModule("../../utils/checkAccuracy.js");

// ✅ 读取历史开奖数据（模拟全部）
const allValues = readAllValues("m");

// ✅ 号码池（01 ~ 49）
const allNumbers = Array.from({ length: 49 }, (_, i) =>
  (i + 1).toString().padStart(2, "0")
);

// ✅ 是否使用窗口
const useWindow = true;

// ✅ 计算遗漏期数（从最近一期开始）
function calculateMissedPeriods(temp) {
  const missedPeriods = {};

  // 初始化每个号码的遗漏期数
  allNumbers.forEach((num) => {
    missedPeriods[num] = 0;
  });

  // 反向遍历最近的历史数据，计算每个号码的遗漏期数
  for (let i = temp.length - 1; i >= 0; i--) {
    const number = temp[i].number;
    missedPeriods[number] = i; // 记录每个号码的最新出现期数
  }

  return missedPeriods;
}

/**
 * 基于加权遗漏号策略
 * - 根据遗漏期数加权选择号码，选择遗漏期数较长的号码
 * @param {Array} temp - 当前窗口的数据
 * @returns {Array} - 选择的32个号码
 */
function select32ByWeightedMissed(temp) {
  const missedPeriods = calculateMissedPeriods(temp);

  // 将遗漏期数较长的号码赋予更高的权重
  const scored = allNumbers.map((num) => ({
    number: num,
    score: missedPeriods[num], // 以遗漏期数作为权重
  }));

  // 按照权重降序排列，选择权重最高的前32个号码
  const selected = _.orderBy(scored, ["score"], ["desc"])
    .slice(0, 32) // 选择前32个号码
    .map((item) => item.number);

  return selected;
}

// ✅ 多窗口循环测试结果
const testResults = [];

for (let windowSize = 2; windowSize <= 200; windowSize++) {
  let correct = 0;
  let maxWrongStreak = 0;
  let currentWrongStreak = 0;
  const predictResults = [];

  allValues.forEach((item, index) => {
    const temp = useWindow
      ? allValues.slice(index - windowSize, index)
      : allValues.slice(0, index);

    if (temp.length === 0) return;

    const selectedNumbers = select32ByWeightedMissed(temp);

    if (selectedNumbers.length !== 32) {
      throw new Error("选出的32个号码数量不正确");
    }

    try {
      const isHit = checkAccuracy(selectedNumbers, item.number);
      if (isHit) {
        correct += 1;
        currentWrongStreak = 0;
      } else {
        currentWrongStreak += 1;
        maxWrongStreak = Math.max(maxWrongStreak, currentWrongStreak);
      }
      predictResults.push(selectedNumbers);
    } catch (err) {
      console.error(`❌ checkAccuracy error at index ${index}: ${err.message}`);
    }
  });

  const total = predictResults.length;
  const accuracy = total > 0 ? ((correct / total) * 100).toFixed(2) : 0;

  testResults.push({
    windowSize,
    total,
    correct,
    accuracy: Number(accuracy),
    maxWrongStreak,
  });
}

// ✅ 输出所有窗口测试结果
testResults.forEach((res) => {
  console.log(
    `windowSize = ${res.windowSize}, 准确率 = ${res.accuracy}%, 最大连续错误次数 = ${res.maxWrongStreak}`
  );
});

// ✅ 输出最佳结果
const bestAcc = _.maxBy(testResults, "accuracy");
const bestStable = _.minBy(testResults, "maxWrongStreak");

console.log("\n🎯 最佳准确率窗口:");
console.log(bestAcc);
console.log("\n🧱 最小连续错误窗口:");
console.log(bestStable);
